package cn.wangcy.shop.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.wangcy.shop.model.User;

@Controller
public class UserController {

    /**
     * 跳转到登录页面
     *
     * @param msg   用来传递消息
     * @param model
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String loginPage(String msg, Model model) {
        model.addAttribute("msg", msg);
        return "login";
    }

    /**
     * 登录功能
     *
     * @param user
     * @param model
     * @return
     */
    @PostMapping("/login")
    public String login(User user, Model model) {
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return "index";
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("user", user);
            model.addAttribute("errorMsg", "登录失败");
            return "login";
        }
    }

    /**
     * 加载中心页面
     *
     * @return
     */
    @RequestMapping(value = "/main", method = RequestMethod.GET)
    public String loginPage() {
        return "main";
    }
}
